package com.qvtu.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qvtu.springboot.entity.Account;
import com.qvtu.springboot.entity.Admin;
import com.qvtu.springboot.entity.Employee;
import com.qvtu.springboot.exception.CustomException;
import com.qvtu.springboot.mapper.AdminMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    public void add(Admin admin) {
        String username = admin.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin != null) {
            throw new CustomException("500", "账号已经存在，请更换账号");
        }
        if (StrUtil.isBlank(admin.getPassword())) {
//密码未空时 设置默认密码为admin
            admin.setPassword("admin");
        }
        admin.setRole("ADM");//角色为管理员
        adminMapper.insert(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void update(Admin admin) {
        adminMapper.update(admin);
    }

    public Admin selectById(Integer id) {
        Admin admin=adminMapper.selectById(id);
        return admin;
    }

    public List<Admin> selectAll(Admin admin) {
        List<Admin> list=adminMapper.selectAll(admin);
        return list;
    }

    public void deleteBatch(List<Integer> ids) {
        for(Integer id:ids){
            this.deleteById(id);
        }
    }

    //    分页查询
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

//    登录逻辑
    public Admin login(Account account){
        String username=account.getUsername();
        Admin dbAdmin=adminMapper.selectByUsername(username);
        if(dbAdmin==null){
//为查询到用户
            throw new CustomException("500","账号不存在");
        }
        String password=account.getPassword();
        if (!dbAdmin.getPassword().equals(password)) {
            throw new CustomException("500", "账号或密码错误");
        }
        return dbAdmin;
    }

    public void updatePassword(Account account) {
//        获取页面传来的数据id
        Integer id = account.getId();
//        获取该id的管理员数据
        Admin admin = this.selectById(id);
        if(admin.getPassword().equals(account.getPassword())){//判断页面传来的数据和数据库数据是否一致
            admin.setPassword(account.getNewPassword());//设置新密码
//            调用uodate方法更新数据库内该管理员的密码
            adminMapper.update(admin);
        }else{
//            页面传来的数据和数据库密码对比 不匹配就报错
            throw new CustomException("500","输入的原密码不正确");
        }

    }
}
